<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller {
	
	public $role;
	public $flags;
	public $allowed_flags_id 	= array();
	public $enable_flags 		= FALSE;
	public $temp_permissions_for_test;
	public function __construct()
	{
			parent::__construct();
			$this->load->model('permission_model');
			$this->load->model('role_model');
			$this->load->model('flag_model');
			
			$this->form_validation->set_error_delimiters('', '');
			
			if(!@$this->session->userdata['logged']){
				redirect('/login/');
				die;
			}
			
			if(!$this->check_permission())
				redirect('/welcome/');
				//die('Permission Error');
			
			$this->flags = $this->flag_model->get_flag_role($this->role);
			
			if(isset($this->flags) && is_array($this->flags))
				foreach($this->flags as $row){
					//$allowed_flags[$row->flag_id] =  array($row->name_en,$row->name_ar);
					$this->allowed_flags_id[] = $row->flag_id;
				}
			

			
	}
	
	function check_permission()
	{
		/*
		 * 1. get the role for the user
		 * 2. get the permissions for the role
		 * 3. check the uri if it is valid
		 * 4. return (die) json msg to the user if not valid
		 * 5. return true (die) if valid
		 * 6. Get the flags for companies and contacts
		 */ 
		 
		 
		 $this->role 	= $this->session->userdata['role'];
		 
		 $temp = $this->role_model->find($this->role);
		 $this->enable_flags = $temp->enable_flags;
		 
		 // die ($role);
		  
		 if($this->role == 1) 
			return true;
		
		 // Get list of all allowed permissions id's
		 $list = $this->permission_model->get_role_permission($this->role);

		 $temp_permissions  = array();
		 $permissions 		= array();
		 
		 // Get the Permission depends on the role_permission id
		 foreach($list->result() as $row){
			$temp_permissions[] = $this->permission_model->get_permission($row->permission_id);
		 }
		 
		//Generate Permission array, see below ex:
		/*Array(
				[company] => Array([index] => Main Screen, [add]=>xxx)
				[contact] => Array([index] => Main Screen)
				[welcome] => Array([index] => Main Screen)
				...
				)
		*/
		
		 foreach($temp_permissions as $array)
			foreach($array as $row){
				$permissions[$row->controller][$row->function] = $row->alias_name;
			}
		
		$controller = $this->uri->segment(1) ? $this->uri->segment(1) : '';
		$fun 		= $this->uri->segment(2) ? $this->uri->segment(2) : 'index';
		$this->temp_permissions_for_test = $permissions;
		//die;
		
		if($fun =='save')
			return true;
		elseif (array_key_exists($controller, $permissions))
			if (is_array($permissions[$controller]))
				return isset($permissions[$controller][$fun]) ? true : false;
	}
	
	function log($module, $activity)
	{
		$log = array(
			'user_id'=> $this->session->userdata['user_id'],
			'activity'=> $activity,
			'module'=> $module,
			'created_on'=> date("Y-m-d H:i:s"));
		
		$this->db->insert('bf_activities', $log);
	}
}










